from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator
from django.db.models import Q

import json
import os
from .models import LearningResource


# Create your views here.

@login_required(login_url="/login")
def learning(request):
    """学习资源主页面"""
    if request.method == "POST":
        pass
    return render(request, "learning-resources-with-backend.html")


@require_http_methods(["GET"])
def get_resources(request):
    """获取学习资源列表"""
    try:
        # 获取查询参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 12))  # 每页显示12个资源
        category = request.GET.get('category', '')
        resource_type = request.GET.get('type', '')
        query = request.GET.get('q', '').strip()

        # 构建查询
        queryset = LearningResource.objects.all()

        # 按分类筛选
        if category:
            queryset = queryset.filter(category=category)

        # 按类型筛选
        if resource_type:
            queryset = queryset.filter(type=resource_type)

        # 搜索
        if query:
            queryset = queryset.filter(
                Q(title__icontains=query) |
                Q(description__icontains=query) |
                Q(content__icontains=query)
            )

        # 排序（可改为参数控制）
        queryset = queryset.order_by('-rating')

        # 分页
        paginator = Paginator(queryset, page_size)
        resources_page = paginator.get_page(page)

        # 构建响应数据
        resources_data = []
        for resource in resources_page:
            resources_data.append({
                'id': resource.id,
                'title': resource.title,
                'description': resource.description,
                'content': resource.content,
                'type': resource.type,
                'category': resource.category,
                'duration': resource.duration,
                'rating': float(resource.rating),
                'file_size': resource.file_size or '',
                'download_url': resource.download_url or '',
                'created_at': resource.created_at.isoformat(),
            })

        response_data = {
            'success': True,
            'resources': resources_data,
            'pagination': {
                'current_page': page,
                'total_pages': paginator.num_pages,
                'total_count': paginator.count,
                'has_next': resources_page.has_next(),
                'has_previous': resources_page.has_previous(),
            }
        }
        return JsonResponse(response_data)

    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)
